<template>
  <div class="dashboard-container">
    <!-- 顶部数据卡片 -->
    <el-row :gutter="20">
      <el-col :span="6" v-for="(item, index) in statisticsCards" :key="index">
        <el-card shadow="hover" class="statistics-card">
          <div class="card-header">
            <i :class="item.icon"></i>
            <span>{{ item.title }}</span>
          </div>
          <div class="card-content">
            <span class="number">{{ item.value }}</span>
            <span class="unit">{{ item.unit }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 文章统计 -->
      <el-col :span="8">
        <el-card shadow="hover">
          <div slot="header">
            <span>文章状态统计</span>
            <el-button type="primary" size="small" style="float: right" @click="handlePublish">
              发布文章
            </el-button>
          </div>
          <div id="articleChart" class="chart"></div>
        </el-card>
      </el-col>

      <!-- 分类统计 -->
      <el-col :span="8">
        <el-card shadow="hover">
          <div slot="header">分类文章统计</div>
          <div id="categoryChart" class="chart"></div>
        </el-card>
      </el-col>

      <!-- 标签云 -->
      <el-col :span="8">
        <el-card shadow="hover">
          <div slot="header">热门标签</div>
          <div id="tagChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 底部图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 用户活跃度 -->
      <el-col :span="12">
        <el-card shadow="hover">
          <div slot="header">用户活跃度趋势</div>
          <div id="userChart" class="chart"></div>
        </el-card>
      </el-col>

      <!-- 系统监控 -->
      <el-col :span="12">
        <el-card shadow="hover">
          <div slot="header">系统资源监控</div>
          <div id="systemChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import 'echarts-wordcloud' // 添加这行
import { websiteApi } from '@/api'

export default {
  name: 'Dashboard',
  data() {
    return {
      statisticsCards: [
        { title: '文章总数', value: 0, unit: '篇', icon: 'el-icon-document' },
        { title: '用户总数', value: 0, unit: '人', icon: 'el-icon-user' },
        { title: '图片总数', value: 0, unit: '张', icon: 'el-icon-picture' },
        { title: '友链总数', value: 0, unit: '个', icon: 'el-icon-link' }
      ],
      charts: {}
    }
  },
  mounted() {
    this.initCharts()
    this.fetchDashboardData()
  },
  methods: {
    initCharts() {
      // 初始化文章统计图表
      this.charts.article = echarts.init(document.getElementById('articleChart'));
      this.charts.article.setOption({
        tooltip: { trigger: 'item' },
        legend: { bottom: '5%' },
        series: [{
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          label: { show: false },
          labelLine: { show: false },
          data: []
        }]
      });

      // 初始化分类统计图表
      this.charts.category = echarts.init(document.getElementById('categoryChart'));
      this.charts.category.setOption({
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'category', data: [] },
        yAxis: { type: 'value' },
        series: [{
          data: [],
          type: 'bar',
          showBackground: true
        }]
      });

      // 修改标签云图表的初始化配置
      this.charts.tag = echarts.init(document.getElementById('tagChart'))
      this.charts.tag.setOption({
        series: [{
          type: 'wordCloud',
          shape: 'circle',
          left: 'center',
          top: 'center',
          width: '70%',
          height: '80%',
          right: null,
          bottom: null,
          sizeRange: [12, 30],
          rotationRange: [-90, 90],
          rotationStep: 45,
          gridSize: 8,
          drawOutOfBound: false,
          layoutAnimation: true,
          textStyle: {
            fontFamily: 'sans-serif',
            fontWeight: 'bold',
          },
          emphasis: {
            focus: 'self',
            textStyle: {
              shadowBlur: 10,
              shadowColor: '#333'
            }
          },
          data: []
        }]
      })

      // 初始化用户活跃度图表
      this.charts.user = echarts.init(document.getElementById('userChart'));
      this.charts.user.setOption({
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            const data = params[0];
            return `${data.name}<br/>${data.value} 人`;
          }
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            formatter: function (value) {
              return value.split(' ')[1]; // 只显示"月-日"
            }
          }
        },
        yAxis: { type: 'value' },
        series: [{
          data: [],
          type: 'line',
          smooth: true,
          itemStyle: {
            color: function (params) {
              // 根据周几返回对应的颜色
              const colors = [
                '#ff9800', // 周日
                '#2196f3', // 周一
                '#4caf50', // 周二
                '#9c27b0', // 周三
                '#ff5722', // 周四
                '#795548', // 周五
                '#607d8b'  // 周六
              ];
              const date = new Date(params.name);
              return colors[date.getDay()];
            }
          },
          lineStyle: {
            width: 2,
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: '#2196f3'
              }, {
                offset: 1, color: '#81d4fa'
              }]
            }
          },
          areaStyle: {
            opacity: 0.1
          }
        }]
      });

      // 初始化系统监控图表
      this.charts.system = echarts.init(document.getElementById('systemChart'));
      this.charts.system.setOption({
        series: [{
          center:['60%', '50%'],
          type: 'gauge',
          progress: { show: true },
          detail: { valueAnimation: true, formatter: '{value}%' },
          data: [{ value: 0 }]
        }]
      });
    },

    /**
     * 更新图表数据
     */
    async fetchDashboardData() {
      websiteApi.getWebsiteInfo().then((response) => {
        if (response.data.code === 20000) {
          if (response.data.data != null) {
            this.updateCharts(response.data.data)
          }
        }
      }).catch((error) => {
        this.$message.error("获取主页数据失败！")
      })
    },

    /**
     * 更新所有图表数据
     * @param {Object} data - 后端返回的数据
     */
    async updateCharts(data) {
      // 更新顶部统计卡片
      this.statisticsCards = [
        { title: '文章总数', value: data.articleCount, unit: '篇', icon: 'el-icon-document' },
        { title: '用户总数', value: data.userCount, unit: '人', icon: 'el-icon-user' },
        { title: '图片总数', value: data.imageCount, unit: '张', icon: 'el-icon-picture-outline' },
        { title: '友链总数', value: data.linkCount, unit: '个', icon: 'el-icon-link' }
      ]

      // 更新文章状态图表
      this.charts.article.setOption({
        series: [{
          data: data.articleStatusList.map(item => ({
            name: item.name,
            value: item.value,
          }))
        }]
      })

      // 更新分类统计图表
      this.charts.category.setOption({
        xAxis: {
          data: data.categoriesNames
        },
        series: [{
          data: data.categoriesValues
        }]
      })

      // 更新标签云图表
      this.charts.tag.setOption({
        series: [{
          data: data.tagsNames.map(tag => ({
            name: tag.name,
            value: tag.value,
            textStyle: {
              color: this.getRandomColor(),
              fontSize: Math.round(tag.value) + 24 // 根据标签权重设置字体大小
            }
          }))
        }]
      })

      // 更新用户活跃度图表
      this.charts.user.setOption({
        xAxis: {
          data: data.userDates.map(date => {
            const d = new Date(date);
            return `${d.getMonth() + 1}-${d.getDate()} ${['周日', '周一', '周二', '周三', '周四', '周五', '周六'][d.getDay()]}`;
          })
        },
        series: [{
          data: data.userValues
        }]
      })

      // 更新系统监控图表
      this.charts.system.setOption({
        series: [
          {
            center:['30%', '50%'],
            data: [
              {
                value: data.cpu,
                name: "cpu占用(%)",
                title: {
                  offsetCenter: ['200%', '-100%']
                },
                detail: {
                  offsetCenter: ['270%', '-100%']
                }
              },
              {
                value: data.memory,
                name: '内存占用(%)',
                title: {
                  offsetCenter: ['200%', '-20%']
                },
                detail: {
                  offsetCenter: ['270%', '-20%']
                }
              },
              {
                value: data.disk,
                name: '磁盘占用(%)',
                title: {
                  offsetCenter: ['200%', '60%']
                },
                detail: {
                  offsetCenter: ['270%', '60%']
                }
              }
            ],
            type: 'gauge',
            anchor: {
              show: true,
              showAbove: true,
              size: 18,
              itemStyle: {
                color: '#FAC858'
              }
            },
            pointer: {
              icon: 'path://M2.9,0.7L2.9,0.7c1.4,0,2.6,1.2,2.6,2.6v115c0,1.4-1.2,2.6-2.6,2.6l0,0c-1.4,0-2.6-1.2-2.6-2.6V3.3C0.3,1.9,1.4,0.7,2.9,0.7z',
              width: 8,
              length: '80%',
              offsetCenter: [0, '8%']
            },
            progress: {
              show: true,
              overlap: true,
              roundCap: true
            },
            axisLine: {
              roundCap: true
            },
            title: {
              fontSize: 14
            },
            detail: {
              width: 40,
              height: 14,
              fontSize: 14,
              color: '#fff',
              backgroundColor: 'inherit',
              borderRadius: 3,
              formatter: '{value}%'
            }
          }
        ]
      })
    },

    /**
     * 生成随机颜色 - 用于标签云
     */
    getRandomColor() {
      const colors = [
        '#3498db', '#2ecc71', '#e74c3c', '#f1c40f',
        '#9b59b6', '#1abc9c', '#e67e22', '#34495e'
      ]
      return colors[Math.floor(Math.random() * colors.length)]
    },

    /**
     * 写文章
     */
    handlePublish() {
      this.$router.push('/articles')
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.statistics-card {
  height: 120px;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.card-header i {
  font-size: 20px;
  margin-right: 10px;
}

.card-content {
  text-align: center;
}

.card-content .number {
  font-size: 24px;
  font-weight: bold;
  margin-right: 5px;
}

.chart-row {
  margin-bottom: 20px;
}

.chart {
  height: 300px;
}
</style>